
"""
用于进行单颗测试
"""


import sys
import time
from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QLabel, 
                           QPushButton, QGroupBox, QGridLayout, QTextEdit, 
                           QProgressBar, QSpinBox, QCheckBox, QComboBox,
                           QMessageBox, QTableWidget, QTableWidgetItem,QLineEdit,
                           QHeaderView, QTabWidget)
from PyQt5.QtCore import Qt, QThread, pyqtSignal, QTimer
from PyQt5.QtGui import QFont, QColor, QPalette

from serial_handler import NSA5312CommandHelper
from serial_protocol import CommandCode, StatusCode

class OneTestWidget(QWidget):

    def __init__(self, command_helper: NSA5312CommandHelper):
        super().__init__()
        self.command_helper = command_helper
        self.init_ui()

    def init_ui(self):
        """初始化UI"""
        layout = QVBoxLayout()
        # GPIO控制组
        gpio_group = QGroupBox("GPIO控制")
        gpio_layout = QGridLayout()
        # 行控制
        gpio_layout.addWidget(QLabel("行控制:"), 0, 0)
        self.row_channel_combo = QComboBox()
        self.row_channel_combo.addItems([str(i) for i in range(1, 9)])  # 显示1-8
        gpio_layout.addWidget(self.row_channel_combo, 0, 1)
        
        row_btn = QPushButton("设置行")
        row_btn.clicked.connect(self.set_row_control)
        gpio_layout.addWidget(row_btn, 0, 2)
        
        # 列控制
        gpio_layout.addWidget(QLabel("列控制:"), 1, 0)
        self.col_channel_combo = QComboBox()
        self.col_channel_combo.addItems([str(i) for i in range(1, 9)])  # 显示1-8
        gpio_layout.addWidget(self.col_channel_combo, 1, 1)
    
        col_btn = QPushButton("设置列")
        col_btn.clicked.connect(self.set_col_control)
        gpio_layout.addWidget(col_btn, 1, 2)
        
        gpio_group.setLayout(gpio_layout)
        layout.addWidget(gpio_group)

        # OWI校准模式组
        owi_cal_group = QGroupBox("OWI校准模式")
        owi_cal_layout = QGridLayout()
        
        # 0x23: OWI校准模式
        owi_cal_layout.addWidget(QLabel("校准模式 (0x23):"), 0, 0)
        self.owi_cal_combo = QComboBox()
        self.owi_cal_combo.addItems(["关闭 (0x00)", "开启 (0x01)"])
        self.owi_cal_combo.setCurrentIndex(1)  # 默认开启
        owi_cal_layout.addWidget(self.owi_cal_combo, 0, 1)
        
        owi_cal_btn = QPushButton("执行OWI校准")
        owi_cal_btn.clicked.connect(self.owi_calibration_mode)
        owi_cal_layout.addWidget(owi_cal_btn, 0, 2)
        
        # 校准状态显示
        self.owi_cal_status_label = QLabel("未执行")
        owi_cal_layout.addWidget(self.owi_cal_status_label, 0, 3)

        owi_cal_group.setLayout(owi_cal_layout)
        layout.addWidget(owi_cal_group)

        # 电源和接口控制组
        power_group = QGroupBox("电源和接口控制")
        power_layout = QGridLayout()
        
        # 0x20: 8路电源控制
        power_layout.addWidget(QLabel("8路电源控制 (0x20):"), 0, 0)
        self.power_control_spin = QSpinBox()
        self.power_control_spin.setRange(0, 255)
        self.power_control_spin.setDisplayIntegerBase(16)
        self.power_control_spin.setPrefix("0x")
        power_layout.addWidget(self.power_control_spin, 0, 1)
        
        power_btn = QPushButton("设置电源")
        power_btn.clicked.connect(self.set_power_control)
        power_layout.addWidget(power_btn, 0, 2)
        
        # 0x21: 5V/6.5V切换
        power_layout.addWidget(QLabel("电压切换 (0x21):"), 1, 0)
        self.voltage_combo = QComboBox()
        self.voltage_combo.addItems(["5V (0x00)", "6.5V (0x01)"])
        power_layout.addWidget(self.voltage_combo, 1, 1)
        
        voltage_btn = QPushButton("切换电压")
        voltage_btn.clicked.connect(self.switch_voltage)
        power_layout.addWidget(voltage_btn, 1, 2)
        self.power_status_label = QLabel("待切换")
        power_layout.addWidget(self.power_status_label, 1, 3)
        
        # 0x22: COM接口切换
        power_layout.addWidget(QLabel("接口切换 (0x22):"), 2, 0)
        self.interface_combo = QComboBox()
        self.interface_combo.addItems(["OWI (0x00)", "AOUT (0x01)"])
        power_layout.addWidget(self.interface_combo, 2, 1)

        
        interface_btn = QPushButton("切换接口")
        interface_btn.clicked.connect(self.switch_interface)
        power_layout.addWidget(interface_btn, 2, 2)
        self.interface_status_label = QLabel("待切换")
        power_layout.addWidget(self.interface_status_label, 2, 3)
        
        power_group.setLayout(power_layout)
        layout.addWidget(power_group)




        layout.addStretch()
        self.setLayout(layout)

    def set_row_control(self):
        """设置行控制"""
        try:
            selected_index = int(self.row_channel_combo.currentText())
            channel = 2 ** (selected_index - 1)  # 计算2的幂次方
            response = self.command_helper.control_gpio_row(channel)
            
            if not response.success:
                QMessageBox.warning(self, "错误", f"设置行控制失败: {response.error_msg}")
        except Exception as e:
            QMessageBox.critical(self, "错误", f"设置行控制异常: {str(e)}")
    
    def set_col_control(self):
        """设置列控制"""
        try:
            selected_index = int(self.col_channel_combo.currentText())
            channel = 2 ** (selected_index - 1)  # 计算2的幂次方
            response = self.command_helper.control_gpio_col(channel)
            
            if not response.success:
                QMessageBox.warning(self, "错误", f"设置行控制失败: {response.error_msg}")
        except Exception as e:
            QMessageBox.critical(self, "错误", f"设置行控制异常: {str(e)}")

    def owi_calibration_mode(self):
        """OWI校准模式 (0x23)"""
        try:
            mode = self.owi_cal_combo.currentIndex()  # 0=关闭, 1=开启
            params = bytes([mode])
            response = self.command_helper.send_custom_command(0x23, params)
            
            if response.success:
                mode_text = "开启" if mode == 1 else "关闭"
                self.owi_cal_status_label.setText(f"校准模式: {mode_text}")
            else:
                self.owi_cal_status_label.setText("执行失败")
        except Exception as e:
            self.show_error("OWI校准模式异常", str(e))

    def show_error(self, title, message):
        """显示错误消息"""
        QMessageBox.warning(self, title, message)

    def set_power_control(self):
        """设置8路电源控制 (0x20)"""
        try:
            value = self.power_control_spin.value()
            # 使用自定义命令发送0x20
            params = bytes([value])
            response = self.command_helper.send_custom_command(0x20, params)
            
            if response.success:
                self.log_result(f"设置8路电源成功: 0x{value:02X}")
            else:
                self.show_error("设置8路电源失败", response.error_msg)
        except Exception as e:
            self.show_error("设置8路电源异常", str(e))


    def switch_voltage(self):
        """切换电压 (0x21)"""
        try:
            index = self.voltage_combo.currentIndex()
            value = index  # 0=5V, 1=6.5V
            params = bytes([value])
            response = self.command_helper.send_custom_command(0x21, params)
            
            if response.success:
                voltage_text = "5V" if value == 0 else "6.5V"
                self.power_status_label.setText(f"设置#{voltage_text}#成功")
            else:
                self.show_error("切换电压失败", response.error_msg)
        except Exception as e:
            self.show_error("切换电压异常", str(e))


    def switch_interface(self):
        """切换接口 (0x22)"""
        try:
            index = self.interface_combo.currentIndex()
            value = index  # 0=OWI, 1=AOUT
            params = bytes([value])
            response = self.command_helper.send_custom_command(0x22, params)
            
            if response.success:
                interface_text = "OWI" if value == 0 else "AOUT"
                self.interface_status_label.setText(f"设置#{interface_text}#成功")
            else:
                self.show_error("切换接口失败", response.error_msg)
        except Exception as e:
            self.show_error("切换接口异常", str(e))